﻿(function ($) {
    var $ErrorDialogDivFormDialog = null;

    //FUNCION PARA CREAR LA BASE DEL FORMULARIO DE DIALOGO QUE SE QUIERE MOSTRAR
    $.createDialogForm = function (param) {
        //Establecemos los valores por defecto
        dialogForm_def = {
            width: 'auto',
            height: 'auto',
            title: '',
            modal: true,
            resizable: false,
            position: 'center',
            CancelButtonText: 'Cancelar',
            SaveButtonText: 'Guardar',
            validarForm: true,
            msgTrySave: 'Intentado efectuar la operación…',
            actionDataSubmit: '',
            TitleMsgError: 'Ocurrio un error en el sistema',
            SaveDataSuccess: ''
        }
        dialogOptions = jQuery.extend(dialogForm_def, param);

        var $dialogo = $('<div></div>');
        $dialogo.append('<form id="jtable-create-form" class="jtable-dialog-form" method="POST" action="'+ dialogOptions.actionDataSubmit +'"></form>');
        $dialogo.dialog({
            autoOpen: false,
            width: dialogOptions.width,
            height: dialogOptions.height,
            modal: dialogOptions.modal,
            title: dialogOptions.title,
            resizable: dialogOptions.resizable,
            position: dialogOptions.position,
            buttons:
                        [{ //Save button
                            id: 'AddRecordDialogSaveButton',
                            text: dialogOptions.SaveButtonText,
                            click: function () {
                                var $saveButton = $('#AddRecordDialogSaveButton');
                                var $addRecordForm = $dialogo.find('form');

                                if (dialogOptions.validarForm) {
                                    if ($addRecordForm.validationEngine('validate') != false) {
                                        _setButtonFormDialogState($saveButton, false, dialogOptions.msgTrySave);
                                        _saveDialogFormData($addRecordForm, $saveButton, dialogOptions);
                                    }
                                } else {
                                    //Si no es necesario la validacion
                                    _setButtonFormDialogState($saveButton, false, dialogOptions.msgTrySave);
                                    _saveDialogFormData($addRecordForm, $saveButton, dialogOptions);
                                }
                            }
                        }, { //Cancel button
                            text: dialogOptions.CancelButtonText,
                            click: function () {
                                $dialogo.dialog('close');
                            }
                        }],
            close: function () {
                var $addRecordForm = $dialogo.find('form').first();
                var $saveButton = $('#AddRecordDialogSaveButton');
                //Removemos el motor de validaciones
                $addRecordForm.validationEngine('hide');
                $addRecordForm.validationEngine('detach');
                _setButtonFormDialogState($saveButton, true, dialogOptions.SaveButtonText);
                $addRecordForm.remove();
                $dialogo.remove();
                $ErrorDialogDivFormDialog.remove();
            }
        });

        //Creamos el DIV que contenera los errores
        _createDivErrorFormDialog(dialogOptions.TitleMsgError);

        //Retornamos el nuevo Form para que se le puedan agregar campos
        return $dialogo;
    };


    //EXTENSION PARA CREAR LOS CAMPOS EN EL FORMULARIO QUE HEMOS CREADO
    $.fn.crearNuevoCampo = function (paramField) {
        var $self = this;
        var $contenedor = $self.find('form').first();
        if (!$contenedor) return;  //Comprobamos que el objeto posee el contenedor de campos

        //Establecemos los valores por defecto
        newField_default = {
            IDField: '',
            Label: "",
            Text: "",
            Validaciones: "",
            Tipo: 'text',
            Width: 'auto',
            MaxLenght: 100,
            MarcaAgua: '',
            Items: {},
            ItemSelectedValue: '0',
            ReadOnly: false,
            Hidden: false
        }
        dialogFieldOptions = jQuery.extend(newField_default, paramField);
        
        //Creamos el contenedor del campo, y el label
        var $newField = $('<div class="jtable-input-field-container"></div>');
        $newField.append('<div class="jtable-input-label">' + dialogFieldOptions.Label + '</div>');

        //Verificamos si el objeto es de solo lectura
        if (dialogFieldOptions.ReadOnly)
            $newField.append('<div class="jtable-input jtable-text-input" style="color: black;">' + dialogFieldOptions.Text + '</div>');
        else {
            //Comprobamos que tipo de campo es
            switch (dialogFieldOptions.Tipo) {
                case 'text':
                    $newField.append('<div class="jtable-input jtable-text-input"><input class="' + dialogFieldOptions.Validaciones + '" id="field-' + dialogFieldOptions.IDField + '" name="' + dialogFieldOptions.IDField + '" type="text" maxlength="' + dialogFieldOptions.MaxLenght + '" value="' + dialogFieldOptions.Text + '" placeholder="'+ dialogFieldOptions.MarcaAgua +'" style="width:' + dialogFieldOptions.Width + ';"></div>');
                    break
                case 'date':
                    $newField.append('<div class="jtable-input jtable-date-input"><input type="text" class="datepick-control ' + dialogFieldOptions.Validaciones + '" id="field-' + dialogFieldOptions.IDField + '" name="' + dialogFieldOptions.IDField + '" maxlength="10" placeholder="dd/mm/aaaa" value="' + dialogFieldOptions.Text + '"></div>');
                    break
                case 'address':
                    $newField.append('<div class="jtable-input jtable-text-input"><textarea id="field-' + dialogFieldOptions.IDField + '" class="' + dialogFieldOptions.Validaciones + '" name="' + dialogFieldOptions.IDField + '" maxlength="' + dialogFieldOptions.MaxLenght + '" rows="2" style="resize:none; width: 318px;">' + dialogFieldOptions.Text + '</textarea></div>');
                    break
                case 'radio':
                    var radioButtonIndex = 0;
                    var $containerDiv = $('<div class="jtable-input jtable-radiobuttonlist-input"></div>');

                    $.each(dialogFieldOptions.Items, function (propName, propValue) {
                        var $radioButtonDiv = $('<div class="jtable-radio-input"></div>').appendTo($containerDiv);
                        var $radioButton = $('<input type="radio" id="field-' + dialogFieldOptions.IDField + (radioButtonIndex++) + '" class="' + dialogFieldOptions.Validaciones + '" name="' + dialogFieldOptions.IDField + '" value="' + propName + '" ' + (dialogFieldOptions.ItemSelectedValue == propName ? 'checked="checked"' : '') + ' />').appendTo($radioButtonDiv);
                        var $textSpan = $('<span>' + propValue + '</span>').appendTo($radioButtonDiv);

                        //Change checkbox state when clicked to text
                        $textSpan.addClass('jtable-option-text-clickable');
                        $textSpan.click(function () {
                            if (!$radioButton.is(':checked')) {
                                $radioButton.attr('checked', true);
                            }
                        });
                    });

                    $containerDiv.appendTo($newField)
                    break
            }
        }

        if (dialogFieldOptions.Hidden)
            $newField.css('display', 'none');

        //Añadimos el nuevo campo en el contenedor de campos
        $contenedor.append($newField);
    };


    /* Establecemos habilitar/deshabilitar el boton cuando se envian los datos
        *************************************************************************/
    function _setButtonFormDialogState($button, enabled, buttonText) {
        if (!$button) {
            return;
        }

        if (enabled != false) {
            $button.removeAttr('disabled').removeClass('ui-state-disabled');
        } else {
            $button.attr('disabled', 'disabled').addClass('ui-state-disabled');
        }

        if (buttonText) {
            $button.find('span').text(buttonText);
        }
    }

    /* Procedimiento para almacenar y mandar los datos al lado del servidor
        *************************************************************************/
    function _saveDialogFormData($addRecordForm, $saveButton, globalOPT) {
        $.SendDataAjax({
            URL: $addRecordForm.attr('action'),
            Parametros: $addRecordForm.serialize(),
            EventSuccess: function () {
                $addRecordForm.parent().dialog("close");
                if (globalOPT.SaveDataSuccess != "") globalOPT.SaveDataSuccess();
            },
            EventError: function (msjError) {
                _setButtonFormDialogState($saveButton, true, globalOPT.SaveButtonText);
                _showErrorDataFormDialog(msjError);
            }
        });
    }

    /* Crea y prepara el "DIV" para mostrar los errores al intentar guardar los cambios
        *************************************************************************/
    _createDivErrorFormDialog = function (titulo) {
        $ErrorDialogDivFormDialog = $('<div></div>');
        $ErrorDialogDivFormDialog.dialog({
            autoOpen: false,
            modal: true,
            title: titulo,
            buttons: [{
                text: 'Aceptar',
                click: function () {
                    $ErrorDialogDivFormDialog.dialog('close');
                }
            }]
        });
    }

    /* Funcion que muestra el mensaje de error especificado en forma de Dialog
        *************************************************************************/
    _showErrorDataFormDialog = function(msgError) {
        $ErrorDialogDivFormDialog.html(msgError).dialog('open');
    }
})(jQuery);